using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

public partial class xPlayerManage : System.Web.UI.UserControl
{
    private Boolean blEdit = false;
    private string MEDIA_DATA = "~/xLitePlayer_data/xMediaPaths.xml";

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnInsert_Click(object sender, EventArgs e)
    {
        MultiView1.SetActiveView(vwInsert);
        Session["blMediaEdit"] = false;
        clearBoxes();
        btnDelete.Visible = false;
    }
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        MultiView1.SetActiveView(vwEdit);
        gvMedia.SelectedIndex = -1;
        fillGrid();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string name = txtName.Text;
        string description = txtDescription.Text;

        description = description.Replace("\r\n", "<br />");

        string imageUrl = lblImageUrl.Text;
        string mediaUrl = lblMedialUrl.Text;

        if ((Session["blMediaEdit"] != null) && ((Boolean)Session["blMediaEdit"]))
        {
            string id = gvMedia.SelectedDataKey.Value.ToString();

            if (lblImageUrl.Text == string.Empty || lblImageUrl.Text == null)
            {
                this.Page.Controls.Add(new LiteralControl(this.ErrorMessage("Please upload an image.")));
                return;
            }
            else if (lblMedialUrl.Text == string.Empty || lblMedialUrl.Text == null)
            {
                this.Page.Controls.Add(new LiteralControl(this.ErrorMessage("Please upload media.")));
                return;
            }
            else
            {

                DataSet tmpDs = new DataSet();

                tmpDs.ReadXml(Server.MapPath(MEDIA_DATA));

                for (int i = 0; i < tmpDs.Tables[0].Rows.Count; i++)
                {
                    if (tmpDs.Tables[0].Rows[i]["id"].ToString() == id)
                    {
                        tmpDs.Tables[0].Rows[i]["details"] = description;
                        tmpDs.Tables[0].Rows[i]["mediaName"] = name;

                        imageUrl = imageUrl.Replace("xLitePlayer_img/", string.Empty);
                        mediaUrl = mediaUrl.Replace("xLitePlayer_media/", string.Empty);

                        tmpDs.Tables[0].Rows[i]["image"] = "xLitePlayer_img/" + imageUrl;
                        tmpDs.Tables[0].Rows[i]["path"] = "xLitePlayer_media/" + mediaUrl;

                        tmpDs.WriteXml(Server.MapPath(MEDIA_DATA));

                        break;
                    }
                }

                this.fillGrid();

                Session["blMediaEdit"] = false;

                MultiView1.SetActiveView(vwEdit);
                btnDelete.Visible = false;
            }

        }
        else
        {
            if (lblImageUrl.Text == string.Empty || lblImageUrl.Text == null)
            {
                this.Page.Controls.Add(new LiteralControl(this.ErrorMessage("Please upload an image.")));
                return;
            }
            else if (lblMedialUrl.Text == string.Empty || lblMedialUrl.Text == null)
            {
                this.Page.Controls.Add(new LiteralControl(this.ErrorMessage("Please upload media.")));
                return;
            }
            else
            {

                DataSet tmpDsSource = new DataSet();
                tmpDsSource.ReadXml(Server.MapPath(MEDIA_DATA));

                DataRow drNewItem;
                drNewItem = tmpDsSource.Tables[0].NewRow();

                drNewItem["id"] = System.Guid.NewGuid().ToString("D");
                drNewItem["mediaName"] = name;
                drNewItem["path"] = "xLitePlayer_media/" + lblMedialUrl.Text;
                drNewItem["image"] = "xLitePlayer_img/" + lblImageUrl.Text;
                drNewItem["details"] = description;

                tmpDsSource.Tables[0].Rows.Add(drNewItem);
                tmpDsSource.WriteXml(Server.MapPath(MEDIA_DATA));

                clearBoxes();
            }

        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        string id = gvMedia.SelectedDataKey.Value.ToString();

        DataSet tmpDs = new DataSet();

        tmpDs.ReadXml(Server.MapPath(MEDIA_DATA));

        for (int i = 0; i < tmpDs.Tables[0].Rows.Count; i++)
        {
            if (tmpDs.Tables[0].Rows[i]["id"].ToString() == id)
            {

                try
                {
                    string imageUrl = "~/" + tmpDs.Tables[0].Rows[i]["image"].ToString();
                    string mediaUrl = "~/" + tmpDs.Tables[0].Rows[i]["path"].ToString();

                    System.IO.File.Delete(Server.MapPath(imageUrl));
                    System.IO.File.Delete(Server.MapPath(mediaUrl));

                    tmpDs.Tables[0].Rows.RemoveAt(i);
                    tmpDs.WriteXml(Server.MapPath(MEDIA_DATA));

                }
                catch (Exception ex)
                {
                    this.Page.Controls.Add(new LiteralControl(this.ErrorMessage("Unable to delete media information.")));
                    return;
                }

                break;
            }
        }

        this.Page.Controls.Add(new LiteralControl(this.SuccessMessage("Media deleted.")));

        clearBoxes();
        gvMedia.DataBind();

        MultiView1.SetActiveView(vwEdit);
        btnDelete.Visible = false;
        gvMedia.SelectedIndex = -1;
    }

    protected void gvMedia_SelectedIndexChanged(object sender, EventArgs e)
    {
        string id = gvMedia.SelectedDataKey.Value.ToString();

        editRow(id);
        Session.Add("blMediaEdit", blEdit);
        Session["blMediaEdit"] = true;
        MultiView1.SetActiveView(vwInsert);
        btnDelete.Visible = true;
    }

    protected void btnAddImage_Click(object sender, EventArgs e)
    {
        string path = "~/xLitePlayer_img/" + fileUpImage.FileName;
        string fileExt = System.IO.Path.GetExtension(fileUpImage.FileName).ToLower();

        if (fileExt != ".jpg")
        {
            this.Page.Controls.Add(new LiteralControl(this.ErrorMessage("Only .jpg images are accepted.")));
            return;
        }

        if (saveFile(path, fileUpImage))
        {
            lblImageUrl.Text = fileUpImage.FileName;
        }
        else
        {
            lblImageUrl.Text = "Unable to upload image.";
            clearBoxes();
        }
    }

    protected void btnAddMedia_Click(object sender, EventArgs e)
    {
        string path = "~/xLitePlayer_media/" + FileUpMedia.FileName;

        string fileExt = System.IO.Path.GetExtension(FileUpMedia.FileName).ToLower();

        if (fileExt != ".wmv")
        {
            this.Page.Controls.Add(new LiteralControl(this.ErrorMessage("Only WMV videos are accepted.")));
            return;
        }


        if (saveFile(path, FileUpMedia))
        {
            lblMedialUrl.Text = FileUpMedia.FileName;
        }
        else
        {
            lblMedialUrl.Text = "Unable to upload media.";
            clearBoxes();
        }
    }

    private void editRow(string id)
    {
        DataSet tmpDs = new DataSet();

        tmpDs.ReadXml(Server.MapPath(MEDIA_DATA));

        for (int i = 0; i < tmpDs.Tables[0].Rows.Count; i++)
        {
            if (tmpDs.Tables[0].Rows[i]["id"].ToString() == id)
            {
                string description = tmpDs.Tables[0].Rows[i]["details"].ToString();

                description = description.Replace("<br />", "\r\n");

                txtDescription.Text = description;
                txtName.Text = tmpDs.Tables[0].Rows[i]["mediaName"].ToString();
                lblImageUrl.Text = tmpDs.Tables[0].Rows[i]["image"].ToString();
                lblMedialUrl.Text = tmpDs.Tables[0].Rows[i]["path"].ToString();
                break;
            }
        }
    }

    private void clearBoxes()
    {
        txtDescription.Text = "";
        txtName.Text = "";
        lblImageUrl.Text = "";
        lblMedialUrl.Text = "";
    }

    private void fillGrid()
    {
        DataSet tmpDs = new DataSet();

        tmpDs.ReadXml(Server.MapPath(MEDIA_DATA));

        string[] keyNames = new string[] { "id" };

        gvMedia.DataSource = tmpDs;
        gvMedia.DataKeyNames = keyNames;
        gvMedia.DataBind();
    }

    private bool saveFile(string physicalPath, System.Web.UI.WebControls.FileUpload fileUp)
    {

        try
        {
            fileUp.PostedFile.SaveAs(Server.MapPath(physicalPath));

            return true;
        }
        catch (Exception)
        {
            return false;
        }

    }

    #region "Error / Success Messages"
    private string ErrorMessage()
    {
        string strScript = null;
        StringBuilder strBldr = new StringBuilder();

        strBldr.Append("<script lang='javascript'>");
        strBldr.Append("alert('Error processing your request.\\n");
        strBldr.Append("Please close your web browser.');");
        strBldr.Append("</script>");

        strScript = strBldr.ToString();

        return strScript;
    }

    private string ErrorMessage(string ErrorMessage)
    {
        string strScript = null;
        StringBuilder strBldr = new StringBuilder();

        strBldr.Append("<script type=\"text/javascript\">");
        strBldr.Append("alert('Error processing your request.\\n");
        strBldr.Append(ErrorMessage);
        strBldr.Append("');");
        strBldr.Append("</script>");

        strScript = strBldr.ToString();
        return strScript;
    }

    private string SuccessMessage()
    {
        string strScript = null;
        StringBuilder strBldr = new StringBuilder();

        strBldr.Append("<script lang='javascript'>");
        strBldr.Append("alert('Successfully processed your request!");
        strBldr.Append("');");
        strBldr.Append("</script>");

        strScript = strBldr.ToString();

        return strScript;


    }

    private string SuccessMessage(string Message)
    {
        string strScript = null;
        StringBuilder strBldr = new StringBuilder();

        strBldr.Append("<script type=\"text/javascript\">");
        strBldr.Append("alert('Sucessfully processed your request!\\n");
        strBldr.Append(Message);
        strBldr.Append("');");
        strBldr.Append("</script>");

        strScript = strBldr.ToString();
        return strScript;


    }

    #endregion

}
